<?php

namespace App\Services\Warehouse\Services;

use App\Services\Warehouse\Interfaces\FreightSpaceServiceInterface;
use App\Services\Warehouse\Model\FreightSpace;
use Illuminate\Support\Facades\Auth;
use App\Exceptions\ApiV2Exception;
use Illuminate\Support\Facades\DB;

class FreightSpaceService implements FreightSpaceServiceInterface
{
    public function index($request)
    {
        $keywords = $request['keywords'] ?? '';
        $warehouse = $request['warehouse'] ?? '';
        $size = $request['size'] ?? 50;
        $data = FreightSpace::query()
            ->when($keywords, function ($query) use ($keywords) {
                return $query->where('position', 'like', '%' . $keywords . '%');
            })
            ->when($warehouse, function ($query) use ($warehouse) {
                return $query->where('warehouse', $warehouse);
            })
            ->orderBy("updated_at", "desc")
            ->paginate($size);

        $data->appends($request);

        return $data->toArray();
    }

    public function set($request, $id = 0)
    {
        $position = $request['warehouse'].'-'.$request['seat'];
        if ($id) {
            $data = FreightSpace::query()->where('position',$position)->where('id','!=',$id)->first();
            if(!empty($data)){
                throw new ApiV2Exception("仓位编号不能重复");
            }
            $data = FreightSpace::findOrFail($id);
        } else {
            $data = FreightSpace::query()->where('position',$position)->first();
            if(!empty($data)){
                throw new ApiV2Exception("仓位编号不能重复");
            }
            $data = new FreightSpace();
        }
        $request['position'] = $position;
        $request['warehouse'] = $request['warehouse'];
        $request['user_id'] = Auth::id();
        $data->fill($request)->save();
        return $data->toArray();
    }

    public function get($id)
    {
        return FreightSpace::query()->where('id', $id)->firstOrFail()->toArray();
    }

    public function destroy($id)
    {
        $data = FreightSpace::findOrFail($id);
        $data->delete();
    }

    public function information($position){
        $data = DB::table('k_freight_space AS fs')
            ->leftJoin('k_parts_inventory AS inventory', 'fs.id', '=', 'inventory.fs_id')
            ->leftJoin('k_parts AS parts', 'parts.id', '=', 'inventory.parts_id')
            ->where('fs.position','=',$position)
            ->select([
                'fs.*',
                'parts.partsCode AS partsCode',
            ])
            ->first();
        return $data;  
    }
}
